
package com.jf.cloud.im.controller.app;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.jf.cloud.api.multishop.bo.EsShopDetailBO;
import com.jf.cloud.api.multishop.feign.ShopDetailFeignClient;
import com.jf.cloud.api.platform.feign.SysUserClient;
import com.jf.cloud.api.platform.vo.SysUserVO;
import com.jf.cloud.api.product.feign.SpuBrowseLogFeignClient;
import com.jf.cloud.api.product.feign.SpuFeignClient;
import com.jf.cloud.common.cache.util.RedisUtil;
import com.jf.cloud.common.database.dto.PageDTO;
import com.jf.cloud.common.database.vo.PageVO;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.product.vo.SpuVO;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.security.AuthUserContext;
import com.jf.cloud.im.constants.Constant;
import com.jf.cloud.im.constants.SendType;
import com.jf.cloud.im.model.ImMsgBizUser;
import com.jf.cloud.im.service.ImMsgBizUserService;
import com.jf.cloud.im.vo.ConversationVO;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

/**
 * @author zz
 */
@RestController
@RequestMapping("/im")
@Tag(name = "用户聊天接口")
public class UserController {

    @Autowired
    private ImMsgBizUserService imMsgBizUserService;
    @Autowired
    private SysUserClient sysUserClient;
    @Autowired
    private ShopDetailFeignClient shopDetailFeignClient;
    @Autowired
    private SpuBrowseLogFeignClient spuBrowseLogFeignClient;
    @Autowired
    private SpuFeignClient spuFeignClient;

    @PostMapping("/conversations")
    @Operation(summary = "最后的对话信息列表项" , description = "获取最后的对话信息列表项")
    public ResponseEntity<PageVO<ConversationVO>> conversations(PageDTO pageDTO) {
        Long userId = AuthUserContext.get().getUserId();
        PageVO<ImMsgBizUser> imMsgBizUserPage = imMsgBizUserService.pageByUserId(pageDTO, userId);
        List<ImMsgBizUser> imMsgBizUserList = imMsgBizUserPage.getList();
        List<ConversationVO> conversationList = new ArrayList<>();
        for (ImMsgBizUser imMsgBizUser : imMsgBizUserList) {
            ConversationVO conversation = new ConversationVO();
            conversation.setChatType(imMsgBizUser.getSendType());
            conversation.setShopId(imMsgBizUser.getBizId());
            conversation.setUserId(imMsgBizUser.getUserId());
            conversation.setLatestMsg(imMsgBizUser.getLastMsgContent());
            conversation.setUnread(imMsgBizUser.getUserUnreadNum());
            // todo 东8区，不应该写死"+8"后续优化
            conversation.setTimestamp(imMsgBizUser.getLastMsgTime().toInstant(ZoneOffset.of("+8")).toEpochMilli());
            conversation.setTimeStr(DateUtil.format(Date.from(imMsgBizUser.getLastMsgTime().atZone(ZoneId.systemDefault()).toInstant()), "yyyy/MM/dd"));
            conversation.setLatestMsgTime(imMsgBizUser.getLastMsgTime());
            conversation.setType(imMsgBizUser.getLastMsgType());
            conversation.setEmployeeId(imMsgBizUser.getEmployeeId());
            if (Objects.equals(imMsgBizUser.getSendType(), SendType.PLATFORM)) {
                ServerResponseEntity<SysUserVO> sysUserResponse = sysUserClient.getSysUserByUserId(imMsgBizUser.getEmployeeId());
                if (!sysUserResponse.isSuccess()) {
                    throw new LuckException(sysUserResponse.getMsg());
                }
                SysUserVO sysUser = sysUserResponse.getData();
                if (sysUser != null) {
                    conversation.setFriendName(sysUser.getNickName());
                }
            } else if (Objects.equals(imMsgBizUser.getSendType(), SendType.SHOP)) {
                ServerResponseEntity<EsShopDetailBO> shopResponse = shopDetailFeignClient.getShopByShopId(imMsgBizUser.getBizId());
                if (!shopResponse.isSuccess()) {
                    throw new LuckException(shopResponse.getMsg());
                }
                EsShopDetailBO shopDetail = shopResponse.getData();
                if (shopDetail != null && shopDetail.getShopStatus() != null) {
                    conversation.setPic(shopDetail.getShopLogo());
                    conversation.setFriendName(shopDetail.getShopName());
                    conversation.setShopStatus(shopDetail.getShopStatus());
                }
            }
            if (Objects.equals(conversation.getChatType(), SendType.SHOP)) {
                Set<String> set2 = RedisUtil.keys(Constant.ONLINE_SHOP_EMPLOYEE_PREFIX + conversation.getShopId() + Constant.UNDERLINE + "*");
                if (set2.isEmpty()) {
                    conversation.setIsOnline(false);
                } else {
                    conversation.setIsOnline(true);
                }
            } else if (Objects.equals(conversation.getChatType(), SendType.PLATFORM)) {
                Set<String> set2 = RedisUtil.keys(Constant.ONLINE_SYS_PREFIX + "*");
                if (set2.isEmpty()) {
                    conversation.setIsOnline(false);
                } else {
                    conversation.setIsOnline(true);
                }
            }
            conversationList.add(conversation);
        }
        PageVO<ConversationVO> conversationPage = new PageVO<>();
        BeanUtils.copyProperties(imMsgBizUserPage, conversationPage);
        conversationPage.setList(conversationList);
        return ResponseEntity.ok(conversationPage);
    }

    @GetMapping("/recentBrowse")
    @Operation(summary = "最近浏览的商品" , description = "获取最近浏览的商品")
    public ResponseEntity<List<SpuVO>> recentBrowse(@ParameterObject Long shopId) {
        Long userId = AuthUserContext.get().getUserId();
        ServerResponseEntity<List<Long>> serverResponseEntity = spuBrowseLogFeignClient.recentBrowse(userId,shopId);
        if (!serverResponseEntity.isSuccess()) {
            throw new LuckException(serverResponseEntity.getMsg());
        }
        List<Long> spuIds = serverResponseEntity.getData();
        if (CollectionUtil.isEmpty(spuIds)) {
            return ResponseEntity.ok(Collections.emptyList());
        }
        ServerResponseEntity<List<SpuVO>> spuResponse = spuFeignClient.listSpuBySpuIds(spuIds);
        if (!spuResponse.isSuccess()) {
            throw new LuckException(spuResponse.getMsg());
        }
        List<SpuVO> spuVOList = spuResponse.getData();
        return ResponseEntity.ok(spuVOList);
    }

}
